package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.Dept;
import com.itheima.service.system.DeptService;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = "/system/dept")
public class DeptController extends BaseController {

    @Autowired
    private DeptService deptService;


    @RequestMapping(value = "/list", name = "分页查询部门列表")
    @RequiresPermissions("部门管理")
    public String findAll(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer size){
        /*List<Dept> depts = deptService.findAll();
        request.setAttribute("depts", depts);*/
        PageInfo<Dept> pageInfo = deptService.findByPage(page, size,companyId);
        request.setAttribute("page",pageInfo);
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toUpdate", name = "跳转到部门修改页面")
    @RequiresPermissions("修改部门")
    public String toUpdate(String id){
        Dept dept = deptService.findById(id);
        List<Dept> list = deptService.findAll(companyId);
        request.setAttribute("deptList",list);
        request.setAttribute("dept", dept);
        return "/system/dept/dept-update";
    }

    @RequestMapping(value = "/toAdd", name = "跳转到部门增加页面")
    @RequiresPermissions("新增部门")
    public String toAdd(){
        List<Dept> list = deptService.findAll(companyId);
        request.setAttribute("deptList",list);
        return "/system/dept/dept-add";
    }

    @RequestMapping(value = "/edit", name = "编辑部门信息")
    public String edit(Dept dept){
        if (StringUtils.isEmpty(dept.getParent().getId())){
            dept.getParent().setId(null);
        }
        dept.setCompanyId(companyId);
        dept.setCompanyName(companyName);
        if (StringUtils.isEmpty(dept.getId())){
            dept.setId(UUID.randomUUID().toString());
            deptService.save(dept);
        } else {
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/delete", name = "删除部门信息")
    @RequiresPermissions("删除部门")
    public String delete(String id){
        deptService.delete(id);
        return "redirect:/system/dept/list.do";
    }

}
